import React, { useState, useEffect } from 'react';
import { randomKey } from '../../../../../utils/utils';
import { Menu } from 'antd';
const { SubMenu } = Menu;

export default function menuMent(props) {
  const [menuList, setMenuItem] = useState([]);
  const [ids, setIds] = useState('');
  useEffect(() => {
    cuttingList(props.value);
  }, [props.value]);
  const tupleObj = {
    components: '组件',
    fields: '字段',
    event: '事件',
    features: '指标',
    strategies: '策略',
    template_list: '策略模板',
  };
  // 切割返回数组
  function cuttingList(data) {
    const datas = [];
    for (let i in data) {
      let newObj = {};
      if (tupleObj[i] && Array.isArray(data[i])) {
        const newLists = data[i].map((item) => {
          item.porary_id = randomKey();
          return item;
        });
        newObj = {
          title: tupleObj[i],
          common: i,
          data: newLists,
        };
        datas.push(newObj);
      } else if (tupleObj[i] && !Array.isArray(data[i])) {
        data[i].porary_id = randomKey();
        newObj = {
          title: tupleObj[i],
          common: i,
          data: [data[i]],
        };
        datas.push(newObj);
      }
    }
    const ids = (datas.length && datas[0].data[0].id) || '';
    setIds(ids);
    datas.length && props.setData({ common: datas[0].common, datas: datas[0].data[0] });
    setMenuItem(datas);
  }
  // 点击返回
  const handleClick = (e) => {
    menuList.forEach((item) => {
      item.data.forEach((it) => {
        if (it.porary_id === e.key) {
          const data = {
            common: item.common,
            datas: it,
          };
          setIds(it.porary_id);
          props.setData(data);
        }
      });
    });
  };
  return (
    <Menu mode='inline' selectedKeys={[ids]} onClick={handleClick}>
      {menuList.map((item, index) => {
        return (
          <SubMenu key={index} title={item.title}>
            {item.data.map((it, idx) => {
              return <Menu.Item key={it.porary_id}>{it.name}</Menu.Item>;
            })}
          </SubMenu>
        );
      })}
    </Menu>
  );
}
